package util

import (
	"gpt-api/framework/log"
	"time"
)

func TimestampToDayBegin(utcLoc *time.Location, zone int) int64 {
	now := time.Now().Add(time.Duration(zone) * time.Hour)
	return time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, utcLoc).Unix() - int64(zone)*3600
}

func ToDayBegin(t time.Time, utcLoc *time.Location, zone int) int64 {
	now := t.In(utcLoc).Add(time.Duration(zone) * time.Hour)
	return time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, utcLoc).Unix() - int64(zone)*3600
}

var locSG, locCN, locUS, locJP *time.Location

func init() {
	locSG, _ = time.LoadLocation("Asia/Singapore")
	locCN, _ = time.LoadLocation("Asia/Shanghai")
	locUS, _ = time.LoadLocation("America/New_York")
	locJP, _ = time.LoadLocation("Asia/Tokyo")
}

func GetMarketTimeZone(market string) *time.Location {
	switch market {
	case "SG":
		return locSG
	case "HK", "CN":
		return locCN
	case "US":
		return locUS
	case "JP":
		return locJP
	default:
	}

	return locCN
}

func CheckNewActivateDay(lastTime time.Time) bool {
	now := time.Now()

	nowNum := now.Year()*10000 + int(now.Month())*100 + now.Day()*1
	lastNum := lastTime.Year()*10000 + int(lastTime.Month())*100 + lastTime.Day()*1

	if nowNum > lastNum {
		return true
	}

	return false
}

func GetCurrentUTCDateSting() string {
	return time.Now().UTC().Format("2006-01-02")
}

func GetCurrentUTCUnixTime() int64 {
	now := time.Now().UTC()
	return time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.UTC).Unix()
}

func TimestampDayBegin(t int64, utcLoc *time.Location, zone int) time.Time {
	//时间戳转时间
	now := time.Unix(t, 0)
	tstamp := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, utcLoc).Unix() - int64(zone)*3600
	return TimestampToTime(tstamp)
}

func TimestampDayEnd(t int64, utcLoc *time.Location, zone int) time.Time {
	now := time.Unix(t, 0)
	tstamp := time.Date(now.Year(), now.Month(), now.Day(), 23, 59, 59, 0, utcLoc).Unix() - int64(zone)*3600
	return TimestampToTime(tstamp)
}
func TimestampToTime(t int64) time.Time {
	return time.Unix(t, 0)
}
func StrToTimestamp(s string) int64 {
	toBeCharge := s + " 00:00:00"
	timeLayout := "2006-01-02 15:04:05"
	loc, _ := time.LoadLocation("Local")
	theTime, err := time.ParseInLocation(timeLayout, toBeCharge, loc)
	if err != nil {
		log.Error("时间转换失败", log.Var("err", err))
		return 1671011798
	}
	sr := theTime.Unix()
	return sr
}
